package com.eunion.web.character.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.eunion.core.DateJsonProcessor;
import com.eunion.core.LogUtil;
import com.eunion.core.exception.ValidateException;
import com.eunion.web.admin.controller.AdminUserController;
import com.eunion.web.character.entity.CharacterClass;
import com.eunion.web.character.entity.CharacterOption;
import com.eunion.web.character.entity.CharacterTopic;
import com.eunion.web.character.service.CharacterClassService;
import com.eunion.web.character.service.CharacterOptionService;
import com.eunion.web.character.service.CharacterTopicService;
import com.eunion.web.common.base.BaseService;
import com.eunion.web.common.base.BaseTableCommonController;
import com.eunion.web.common.vo.Web;

import net.sf.json.JsonConfig;

@Controller
@RequestMapping(value = "/api/characterTopic")
@PreAuthorize("hasAuthority('character:admin')")
public class CharacterTopicController extends BaseTableCommonController<CharacterTopic, Integer> {
	@Autowired
	private CharacterTopicService characterTopicService;
	@Autowired
	private CharacterClassService characterClassService;
	@Autowired
	private CharacterOptionService characterOptionService;
	@Autowired
	private ApplicationContext applicationContext;

	@Override
	protected BaseService<CharacterTopic, Integer> getBaseService() {
		// TODO Auto-generated method stub
		return characterTopicService;
	}


	@RequestMapping(value = Web.URL_SEP_UPDATE, method = {RequestMethod.POST})
	public String updateCharacterTopic(CharacterTopic characterTopic,String characterClass,BindingResult result, Model model, HttpServletRequest request) {
		
		characterTopic.setXzlx("xzlx01");//默认单选
		characterTopic.setXqlx("mbti_zyxgcp");
		List<CharacterOption> options = characterTopicService.findOne(characterTopic.getId()).getmOpitons();//characterOptionService.findCharacterOptionByTopic(characterTopic.getId()+"");
		String[] lx = characterClass.split("#");
		if(options == null) {
			options = new ArrayList<>();
			
			CharacterOption sOption = new CharacterOption();
			sOption.setContent("是");
			sOption.setFz("1");	
			sOption.setLx(lx[0]);
			sOption.setLxName(lx[1]);
			sOption.setCharacterTopic(characterTopic);
			options.add(sOption);
			CharacterOption fOption = new CharacterOption();
			fOption.setContent("否");
			fOption.setFz("0");
			fOption.setLx(lx[0]);
			fOption.setLxName(lx[1]);
			fOption.setCharacterTopic(characterTopic);
			options.add(fOption);
		} else {
			for(CharacterOption option : options) {
				if(!option.getLx().equals(lx[0])) {
					option.setLx(lx[0]);
					option.setLxName(lx[1]);
				}
			}
		}
		characterTopic.setmOpitons(options);
		characterTopicService.saveAndFlush(characterTopic);
		model.addAttribute(Web.OBJ, characterTopic);
		return getUrlBase().concat("-edit");
	}

	
	/**
	 *  目前默认评测选项均为是或者否,分值默认为1分
	 * @param characterTopic 评测题目
	 * @param characterClass 评测答案对应的性格类型
	 * @param result
	 * @param model
	 * @return
	 */
	@PostMapping(value = Web.URL_SEP_SAVE)
	public String addCharacterTopic(CharacterTopic characterTopic,String characterClass, BindingResult result, Model model, HttpServletRequest request) {
		//checkBindResult(result);
		characterTopic.setXzlx("xzlx01");//默认单选
		characterTopic.setXqlx("mbti_zyxgcp");
		List<CharacterOption> options = characterTopic.getmOpitons();
		if(options == null) {
			String[] lx = characterClass.split("#");
			options = new ArrayList<>();

			CharacterOption sOption = new CharacterOption();
			sOption.setContent("是");
			sOption.setFz("1");
			sOption.setLx(lx[0]);
			sOption.setLxName(lx[1]);
			sOption.setCharacterTopic(characterTopic);
			options.add(sOption);
			CharacterOption fOption = new CharacterOption();
			fOption.setContent("否");
			fOption.setFz("0");
			fOption.setLx(lx[0]);
			fOption.setLxName(lx[1]);
			fOption.setCharacterTopic(characterTopic);
			options.add(fOption);

			characterTopic.setmOpitons(options);
		}
		characterTopicService.save(characterTopic);
		return getUrlBase().concat("-add");
	}


	/**
	 * 进入性格管理页面
	 * @return
	 */
	@RequestMapping("/index")
	public String index() {
		return getUrlBase();
	}

	@Override
	protected String getUrlBase() {
		return "admin/character/charactertopic";
	}
	
	
	protected JsonConfig getJsonConfig() {
        JsonConfig cfg = new JsonConfig();
        // net.sf.json.JSONException: java.lang.reflect.InvocationTargetException异常
        // cfg.setExcludes(new String[]{"handler","hibernateLazyInitializer"});
        //
        // //过滤关联，避免死循环net.sf.json.JSONException: java.lang.reflect.InvocationTargetException
        // cfg.setJsonPropertyFilter(new PropertyFilter() {
        // public boolean apply(Object source, String name, Object value) {
        // if(name.equals("addressGroup")||name.equals("user")||name.equals("createTime")||name.equals("birthday")) {
        // return true;
        // } else {
        // return false;
        // }
        // }
        // });
        //
        // //javabean里出现循环调用啦，赶快用excludes干掉parent或者children
        // cfg.setExcludes(new String[]{"sysUri","sysUris","sysRoleUriLinks"});
        // net.sf.json.JSONException: java.lang.reflect.InvocationTargetException日期格式转化出错
        // cfg.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        cfg.registerJsonValueProcessor(Date.class, new DateJsonProcessor("yyyy-MM-dd HH:mm:ss"));
        cfg.setIgnoreDefaultExcludes(true);
        cfg.setExcludes(new String[] {"characterTopic"});
        return cfg;
    }
}
